package edu.ynu.se.xiecheng.achitectureclass.service.impl;

import edu.ynu.se.xiecheng.achitectureclass.dao.DeviceDao;
import edu.ynu.se.xiecheng.achitectureclass.dao.GreenhouseDao;
import edu.ynu.se.xiecheng.achitectureclass.entity.Device;
import edu.ynu.se.xiecheng.achitectureclass.entity.Greenhouse;
import edu.ynu.se.xiecheng.achitectureclass.service.DeviceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class DeviceServiceImpl implements DeviceService {
    private static final Logger logger = LoggerFactory.getLogger(DeviceServiceImpl.class);

    @Autowired
    private DeviceDao deviceDao;
    
    @Autowired
    private GreenhouseDao greenhouseDao;

    @Override
    public Device bindDeviceToGreenhouse(String deviceSerial, Long greenhouseId) {
        // 获取设备
        Device device = deviceDao.findById(deviceSerial)
            .orElseThrow(() -> new RuntimeException("Device not found: " + deviceSerial));
            
        // 获取大棚
        Greenhouse greenhouse = greenhouseDao.findById(greenhouseId)
            .orElseThrow(() -> new RuntimeException("Greenhouse not found: " + greenhouseId));
            
        // 检查大棚是否已经绑定了同类型的设备
        if (deviceDao.existsByGreenhouseAndDeviceType(greenhouse, device.getDeviceType())) {
            throw new RuntimeException(String.format(
                "Greenhouse already has a %s device", 
                device.getDeviceType().getDisplayName()
            ));
        }
        
        // 绑定设备到大棚
        device.setGreenhouse(greenhouse);
        Device savedDevice = deviceDao.save(device);
        
        logger.info("Device {} ({}) bound to greenhouse {}",
            device.getDeviceType().getDisplayName(),
            deviceSerial,
            greenhouseId);
            
        return savedDevice;
    }

    @Override
    public Device unbindDevice(String deviceSerial) {
        Device device = deviceDao.findById(deviceSerial)
            .orElseThrow(() -> new RuntimeException("Device not found: " + deviceSerial));
            
        Long greenhouseId = device.getGreenhouse() != null ? device.getGreenhouse().getId() : null;
        device.setGreenhouse(null);
        Device savedDevice = deviceDao.save(device);
        
        logger.info("Device {} ({}) unbound from greenhouse {}",
            device.getDeviceType().getDisplayName(),
            deviceSerial,
            greenhouseId);
            
        return savedDevice;
    }
} 